/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managerBeans;

import entity.Users;
import java.io.Serializable;
import java.util.UUID;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.context.RequestContext;
import sessionBeans.UsersFacadeLocal;
import util.MD5;
import util.SendMail;

/**
 *
 * @author Minh Luc
 */
@ManagedBean
@SessionScoped
public class UserBean implements Serializable {

    @EJB
    private UsersFacadeLocal usersFacade;
    private String username = "";
    private String password = "";
    private String passwordTemp = ""; //recovery password
    private String email = "";
    private String answer = "";
    private String MethodRecoverPassword = "";// Phương thức phục hồi mật khẩu.
    private String RegisterCode = "";
    private Users userTemp = null;

    public void ChangePassword() {
        RequestContext context = RequestContext.getCurrentInstance();
        FacesMessage msg = null;
        if (usersFacade.checkLogin(System.user.getUserName(), new MD5().encryptionMD5(password)) != null) {
            System.user.setPassword(new MD5().encryptionMD5(System.user.getPassword()));
            usersFacade.edit(System.user);
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Save Sussecful", "Luu thành công 3 !");
            context.addCallbackParam("edit", true);
        } else {
            msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error Sussecful", "password cu sai !");
        }
        userTemp = null;

        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public void Edit(ActionEvent actionEvent) {

        if (!validateEdit(System.user)) {
            return;
        }

        RequestContext context = RequestContext.getCurrentInstance();
        FacesMessage msg = null;
        try {
            usersFacade.edit(System.user);
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Save Sussecful", "Save Successful !");
        } catch (Exception e) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Save Error", "Save unSuccessful !" + e.getMessage());
        }
        context.addCallbackParam("edit", true);
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public void Logout() {
        setUsername("");
        setPassword("");
        System.user = null;
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Logout Sussecful", "Exit Successful !");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public void Login(ActionEvent actionEvent) {
        RequestContext context = RequestContext.getCurrentInstance();
        FacesMessage msg = null;
        boolean loggedIn = false;
        System.user = usersFacade.checkLogin(username, new MD5().encryptionMD5(password));

        if (System.user != null) {
            if (System.user.getIsLock() || System.user.getRoles() == null) {
                loggedIn = false;
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Account Lock", System.user.getUserName() + " Has block by Manager ");

            } else {
                String roleName = System.user.getRoles().getRoleName();
                loggedIn = true;
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", "Hello, " + System.user.getTitleOfCourtesy() + " " + System.user.getFristName() + " login to "
                        + roleName);// frist user
            }
        } else {
            loggedIn = false;
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid username or password !");
        }
        FacesContext.getCurrentInstance().addMessage(null, msg);
        context.addCallbackParam("loggedIn", loggedIn);
    }

    public void CheckRegisterCode(ActionEvent actionEvent) {
        FacesMessage msg = null;
        RequestContext context = RequestContext.getCurrentInstance();
        setUserTemp(usersFacade.findByCodeRegister(RegisterCode));
        if (getUserTemp() != null) {
            userTemp.setEmail("");
            userTemp.setUserName("");
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "RegisterCode true", "Validate Code Successful!");
            context.addCallbackParam("RegisterCodeSussecful", true);
        } else {
            msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "RegisterCode false", "RegisterCode is InValidate");
        }
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public void RegisterEmployee(ActionEvent actionEvent) {

        if (!validate(userTemp)) {
            return;
        }

        RequestContext context = RequestContext.getCurrentInstance();
        userTemp.setPassword(new MD5().encryptionMD5(userTemp.getPassword()));
        usersFacade.edit(getUserTemp());
        setUserTemp(null);
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Create Sussecful", "Create Account Successful !");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        context.addCallbackParam("RegisterEmployee", true);
    }

    public void SetNewPassword(ActionEvent actionEvent) {
        FacesMessage msg = null;
        RequestContext context = RequestContext.getCurrentInstance();
        getUserTemp().setPassword(new MD5().encryptionMD5(passwordTemp));
        setPasswordTemp("");
        setAnswer("");
        usersFacade.edit(getUserTemp());
        msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "System", "Update Your Password.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        context.addCallbackParam("SetPasswordComplete", true);
    }

    public void RecoverPassword(ActionEvent actionEvent) {

        FacesMessage msg = null;
        RequestContext context = RequestContext.getCurrentInstance();
        if (MethodRecoverPassword.equals("Answer")) {
            setUserTemp(usersFacade.hasAnswer(username, answer));
            if (getUserTemp() != null) {
                context.addCallbackParam("ShowFormSetPassword", true);
            } else {
                msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "System", "Wrong Answer.");
            }
        } else if (MethodRecoverPassword.equals("Email")) {
            setUserTemp(usersFacade.hasEmail(email));
            if (getUserTemp() != null) {
                String pwTemp = UUID.randomUUID().toString().subSequence(0, 8).toString();
                getUserTemp().setPassword(new MD5().encryptionMD5(pwTemp));
                usersFacade.edit(getUserTemp());
                try {
                    SendMail.send(email, "Password Recover", "Username :" + userTemp.getUserName() + "\nNew Password : " + pwTemp);
                } catch (Exception ex) {
                    msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "System", ex.getMessage());
                }
                setUserTemp(null);
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "System", "System send new password to your email");

                context.addCallbackParam("RecoverComplete", true);
            } else {
                msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "System", "System don't see your email");
            }
        }
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public void selectMethodRecoverPassword(ActionEvent actionEvent) {
        RequestContext context = RequestContext.getCurrentInstance();
        context.addCallbackParam("selectMethodRecoverPassword", MethodRecoverPassword);
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getMethodRecoverPassword() {
        return MethodRecoverPassword;
    }

    public void setMethodRecoverPassword(String MethodRecoverPassword) {
        this.MethodRecoverPassword = MethodRecoverPassword;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAnswer() {
        return answer;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }

    public String getPasswordTemp() {
        return passwordTemp;
    }

    public void setPasswordTemp(String passwordTemp) {
        this.passwordTemp = passwordTemp;
    }

    public String getRegisterCode() {
        return RegisterCode;
    }

    public void setRegisterCode(String RegisterCode) {
        this.RegisterCode = RegisterCode;
    }

    public Users getUserTemp() {
        return userTemp;
    }

    public void setUserTemp(Users userTemp) {
        this.userTemp = userTemp;
    }

    //Validate User
    public boolean validate(Users users) {
        RequestContext context = RequestContext.getCurrentInstance();
        FacesMessage msg = null;

        if (users.getUserName() == null || users.getUserName().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Username is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (users.getUserName().length() < 2 || users.getUserName().length() > 30) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Username is from 2 - 30 Characters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isContent2(users.getUserName())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Username is only Character");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getPassword() == null || users.getPassword().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Password is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (users.getPassword().length() < 2 || users.getPassword().length() > 30) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Password is from 2 - 30 Characters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isContent2(users.getPassword())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Password is only Character");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getTitleOfCourtesy() == null || users.getTitleOfCourtesy().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "TitleOfCourtesy is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (users.getTitleOfCourtesy().length() < 2 || users.getTitleOfCourtesy().length() > 16) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "TitleOfCourtesy is greater 2 - 16 Characters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isContent(users.getTitleOfCourtesy())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "TitleOfCourtesy is only Characters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getLastName() == null || users.getLastName().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Lastname is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (users.getLastName().length() < 2 || users.getLastName().length() > 16) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Lastname is from 2 - 16 Letters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isChar(users.getLastName())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Lastname is only Letter");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getFristName() == null || users.getFristName().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Firstname is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (users.getFristName().length() < 2 || users.getFristName().length() > 16) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Firstname is from 2 - 16 Letters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isChar(users.getFristName())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Firstname is only Letter");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getAddress() == null || users.getAddress().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Address is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (users.getAddress().length() < 2 || users.getAddress().length() > 300) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Address is from 2 - 300 Characters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isContent(users.getAddress())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Address is only Character");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getCity() == null || users.getCity().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "City is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (users.getCity().length() < 2 || users.getCity().length() > 30) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "City is greater 2 - 30 Characters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isCharacter(users.getCity())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "City is only Character");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getRegion() == null || users.getRegion().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Region is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (users.getRegion().length() < 2 || users.getRegion().length() > 30) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Region is from 2 - 30 Characters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isCharacter(users.getRegion())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Region is only Character");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getPostalCode() == null || users.getPostalCode().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "PostalCode is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (!(users.getPostalCode().length() == 5)) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "PostalCode is only 5 Numbers");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isInt(users.getPostalCode())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "PostalCode is only number");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getMobilePhone() == null || users.getMobilePhone().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "MobilePhone is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (!util.Validate.isPhone(users.getMobilePhone())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "MobilePhone is from 8 - 14 numbers");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getEmail() == null || users.getEmail().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Email is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (!util.Validate.isValidEmail(users.getEmail())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Format Email is xxx@xxx.xxx");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getAnswer() == null || users.getAnswer().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Answer is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (users.getAnswer().length() < 2 || users.getAnswer().length() > 30) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Answer is from 2 - 30 Characters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isContent(users.getAnswer())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Answer is only Character");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        return true;
    }

    //Validate EditUser
    public boolean validateEdit(Users users) {
        RequestContext context = RequestContext.getCurrentInstance();
        FacesMessage msg = null;

        if (users.getAddress() == null || users.getAddress().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Address is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (users.getAddress().length() < 2 || users.getAddress().length() > 300) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Address is from 2 - 300 Characters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isContent(users.getAddress())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Address is only Character");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getCity() == null || users.getCity().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "City is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (users.getCity().length() < 2 || users.getCity().length() > 30) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "City is greater 2 - 30 Characters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isCharacter(users.getCity())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "City is only Character");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getRegion() == null || users.getRegion().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Region is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (users.getRegion().length() < 2 || users.getRegion().length() > 30) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Region is from 2 - 30 Characters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isCharacter(users.getRegion())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Region is only Character");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getPostalCode() == null || users.getPostalCode().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "PostalCode is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (!(users.getPostalCode().length() == 5)) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "PostalCode is only 5 Numbers");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isInt(users.getPostalCode())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "PostalCode is only number");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getMobilePhone() == null || users.getMobilePhone().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "MobilePhone is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (!util.Validate.isPhone(users.getMobilePhone())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "MobilePhone is from 8 - 14 numbers");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getEmail() == null || users.getEmail().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Email is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (!util.Validate.isValidEmail(users.getEmail())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Format Email is xxx@xxx.xxx");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        if (users.getAnswer() == null || users.getAnswer().length() == 0) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Answer is not null");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return false;
        } else {
            if (users.getAnswer().length() < 2 || users.getAnswer().length() > 30) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Answer is from 2 - 30 Characters");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
            if (!util.Validate.isContent(users.getAnswer())) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Answer is only Character");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return false;
            }
        }
        return true;
    }
}
